package student;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

/*3.	使用DOM4J解析第1题 作业中编写的XML文档，输出所有学员信息，并进行以下操作：
删除id为1的学生成绩信息，修改id为2的成绩为60，添加一个学生的成绩信息（id为5）*/
public class Dom4jParserStudent {
    private final static String path = "D:\\JAVAIDEA\\homework26\\src\\student\\scores.xml";
    SAXReader reader = new SAXReader();
    Scanner input = new Scanner(System.in);

    public void save(Document document){//将传来的文档写进指定的文件中,即保存
        OutputFormat outputFormat = null;
        outputFormat = OutputFormat.createPrettyPrint();
        //使用输出格式类，来更改格式，注意使用一个静态方法来获得输出格式类对象
        outputFormat.setEncoding("UTF-8");//设置想要的格式，如字符集、是否换行、是否缩进
        XMLWriter xmlWriter = null;
        try {
            xmlWriter = new XMLWriter(new FileWriter(path),outputFormat);
            //再使用XMLWriter类将传来的文档写进指定路径中，可以把更改的格式对象当做参数传入
            xmlWriter.write(document);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                xmlWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void add(){//将一个元素添加进文档中
        Document document = null;
        try {
            document = reader.read(new File(path));
            Element rootElement = document.getRootElement();
            Element studentElement = rootElement.addElement("student");
            System.out.print("请输入添加学生的学号：");
            studentElement.addAttribute("id",String.valueOf(input.nextInt()));
            //设置该节点下的子节点
            Element nameElement = studentElement.addElement("name");
            System.out.print("请输入添加学生的姓名：");
            nameElement.setText(input.next());//设置文本内容
            Element courseElement = studentElement.addElement("course");
            System.out.print("请输入添加学生的课程：");
            courseElement.setText(input.next());
            Element scoreElement = studentElement.addElement("score");
            System.out.print("请输入添加学生的分数：");
            scoreElement.setText(input.next());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        save(document);
    }
    public void find(){
        Document document = null;
        try {
            document = reader.read(new File(path));
            Element rootElement = document.getRootElement();
            for (Iterator it = rootElement.elementIterator(); it.hasNext(); ) {//使用迭代器迭代出所有的子元素
                Element stuElement = (Element) it.next();//迭代器转换为的是节点，要转型
                Attribute attribute = stuElement.attribute("id");//取出相应的属性
                System.out.print("学生的学号是：" + attribute.getValue());//打印出值
                for (Iterator iterator = stuElement.elementIterator(); iterator.hasNext();) {
                    Element element = (Element) iterator.next();
                    if (element.getName().equals("name")) {
                        System.out.print("\t学生姓名：" + element.getText());
                    }else if (element.getName().equals("course")) {
                        System.out.print("\t学生的课程：" + element.getText());
                    }else{
                        System.out.print("\t学生的成绩：" + element.getText());
                    }
                }
                System.out.println();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public void delete(){
        System.out.print("请输入你想删除的学生学号：");
        int id = input.nextInt();
        Document document = null;
        try {
            document = reader.read(new File(path));
            Element rootEle = document.getRootElement();
            for (Iterator it = rootEle.elementIterator(); it.hasNext();) {
                Element stuElement = (Element) it.next();
                if (stuElement.attributeValue("id").equals(String.valueOf(id))) {
                    rootEle.remove(stuElement);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        save(document);
    }
    public void  modifier(){
        System.out.print("请输入你想修改的学生学号：");
        int id = input.nextInt();
        System.out.print("请输入你想修改的学生的那个信息：");
        String info = input.next();
        System.out.print("请输入你想修改的内容：");
        String content = input.next();
        Document document = null;
        try {
            document = reader.read(new File(path));
            Element root = document.getRootElement();
            for (Iterator it = root.elementIterator(); it.hasNext();) {
                Element stuElement = (Element) it.next();
                if (stuElement.attributeValue("id").equals(String.valueOf(id))) {
                    switch (info){
                        case "id":
                            Attribute attribute = stuElement.attribute("id");
                            attribute.setValue(content);
                            break;
                        case "name":
                            stuElement.element("name").setText(content);
                            break;
                        case "course":
                            stuElement.element("course").setText(content);
                            break;
                        case "score":
                            stuElement.element("score").setText(content);
                            break;
                        default:
                    }
                }
            }
            save(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Dom4jParserStudent dps = new Dom4jParserStudent();
        dps.find();
        dps.delete();
        dps.modifier();
        dps.add();
    }
}
